package com.huawei.csi.tool.validation;

import com.vladsch.flexmark.ast.Heading;
import com.vladsch.flexmark.ast.Paragraph;
import com.vladsch.flexmark.util.sequence.BasedSequence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author lxw
 */
public class MarkWordVerify extends AbstractVerify {
    /**
     * LOGGER
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(MarkWordVerify.class);

    /**
     * INSTANCE
     */
    private static final MarkWordVerify INSTANCE = new MarkWordVerify();

    /**
     * 校验规则
     */
    private static VerifyRegexEnum verifyRegexEnum;

    private MarkWordVerify() {
    }
    /**
     * getInstance
     *
     * @return com.huawei.csi.tool.validation.MarkWordAbstractVerify2
     **/
    public static MarkWordVerify getInstance(VerifyRegexEnum regexEnum) {
        verifyRegexEnum = regexEnum;
        return INSTANCE;
    }

    private static boolean headVerify(Heading heading, String regex) {
        Pattern pattern = Pattern.compile(regex);  // 编译正则表达式
        BasedSequence text = heading.getText();
        Matcher matcher = pattern.matcher(text);
        boolean matched = matcher.find();
        if (!matched) {
            LOGGER.info("标题不符合规则：{}，{}", text, regex);
        }
        return matched;
    }

    @Override
    boolean verifyHeading(Heading heading) {
        if (verifyRegexEnum != null) {
            String regex = verifyRegexEnum.headRegex;
            if (regex == null || regex.isEmpty()) {
                return true;
            }
            if (verifyRegexEnum.equals(VerifyRegexEnum.CHANGE_LOG)) { // 现在只对二级标题进行检查, 或者后期改成针对不同标题分别进行 正则匹配
                if (heading.getLevel() == 2 &&
                        !HEAD_EXCLUDE_LIST.contains(String.valueOf(heading.getText()))) {
                    return headVerify(heading, regex);
                }
                return true;
            }
            return headVerify(heading, regex);
        }
        return true;
    }

    @Override
    boolean verifyParagraph(Paragraph paragraph) {
        // 如果想对段落进行校验，需要给出 校验规则
        return super.verifyParagraph(paragraph);
    }
}
